<?php


namespace app\api\validate;


use app\lib\exception\parameterException;
use think\Exception;
use think\Request;
use think\Validate;

class BaseValidate extends Validate
{
    // 基类验证整数
    protected function isInt($value, $rule = '', $data = '', $field = '')
    {
        if (is_numeric($value) && is_int($value + 0) && ($value + 0) > 0) {
            return true;
        } else {
            return $field.'必须是正整数';
        }
    }

    // 基类验证参数不能为空
    protected function isNotEmpty($value, $rule = '', $data = '', $field = '')
    {
        if (empty($value)){
            return false;
        } else {
            return true;
        }
    }

    public function goCheck()
    {
        // 获取全部request实例对象
        $request = Request::instance();
        // 获取所有HTTP传入参数
        $param = $request->param();

        $result = $this->batch()->check($param);
        if (!$result) {
            $e = new parameterException([
                'msg' => $this->error
            ]);
            throw $e;
        } else {
            return true;
        }
    }

    // 客户端传递参数验证规则
    public function getDataRules($arrays)
    {
        if (array_key_exists('user_id', $arrays) | array_key_exists('uid', $arrays)) {
            // 不允许传入user_id和uid
            throw new ParameterException([
                'msg' => '参数中包含非法参数名'
            ]);
        }
        $newArray = [];
        // 遍历$rule里面的数组
        foreach ($this->rule as $key => $value) {
            $newArray[$key] = $arrays[$key];
        }
        return $newArray;
    }

    // 验证手机号
    protected function isMobile($value)
    {
        $rule = '^1(3|4|5|7|8)[0-9]\d{8}$^';
        $result = preg_match($rule, $value);
        if ($result) {
            return true;
        } else {
            return false;
        }
    }
}